//上传组件
//<h-modal className="uploader-modal" v-model="open" :close-on-mask="true" :transparent="true">
//</h-modal>
Vue.component('uploader', {
    template: `
        <div class="file-manage">
            <h-layout>
                <h-sider>
                    <div class="file-manage-dire">
                        <div class="create-btn">
                            <h-button noBorder text-color="primary" icon="h-icon-plus" @click="createDirectoryModal=true">新建文件夹</h-button>
                        </div>
                        <div class="file-manage-dire-content">
                            <h-tabs class-name="h-tabs-menu file-manage-dire-tabs" :datas="fileDirectory"
                                key-name="key" title-name="name" v-model="fileDirectorySelected"
                                @change="onChangeDirectory">
                                <template slot-scope="{tab}" slot="item">
                                    <span><i class="icon icon-wenjian1"></i></span>
                                    <span>{{tab.name}}</span>
                                </template>
                            </h-tabs>
                        </div>
                        <div class="dire-title">
                         <div v-show="typeSelected==1">选择文件数量：{{multiple}}</div>
                          <div v-show="typeSelected==2">
                            <div>上传总数量：{{fileNum}}</div>
                            <div>单文件大小：{{fileSingleSizeLimitKB}}</div>
                            <div>总文件大小：{{fileSizeLimitKB}}</div>
                          </div>
                        </div>
                    </div>
                </h-sider>
                <h-layout>
                    <h-header>
                        <div class="file-manage-header">
                            <h-tabs class-name="h-tabs-card" :datas="fileType" key-name="key" title-name="name"
                                v-model="typeSelected" @change="onChangeType">
                            </h-tabs>
                        </div>
                    </h-header>
                    <h-content>
                        <div class="file-manage-content">
                            <div class="online" v-show="typeSelected==1" @scroll="onOnlineScroll($event)">
                                <div class="uploader-list">
                                    <div class="uploader-list-item" v-for="(item, index) in online.file"
                                        :key="index" @click="onOnlineSelected(index)">
                                        <img :src="item.src">
                                        <div class="select-btn" v-show="item.checked">
                                            <i class="h-icon-check"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="uploader" v-show="typeSelected==2">
                                <div class="uploader-list">
                                    <div class="uploader-list-item" v-for="(item, index) in fileListData"
                                        :key="index" @mouseenter="onSenter(index)" @mouseleave="onleavue(index)">
                                        <div class="uploader-list-item-btn" v-show="item.closeBtnShow"
                                            v-if="item.errorCode!=1">
                                            <span class="close" title="移除" @click="onRemoveFile(item.id,index)"><i
                                                    class="h-icon-trash"></i></span>
                                        </div>
                                        <div class="uploader-list-item-title"
                                            :class="[item.errorCode==2 ? 'error':'']" v-show="item.errorCode>0">
                                            {{item.errorMsg}}
                                        </div>
                                        <img :src="item.src">
                                        <div class="uploader-list-item-file-progress">
                                            <h-progress :percent="item.progress" color="#45B984" :stroke-width="6">
                                            </h-progress>
                                        </div>
                                        <div class="uploader-list-item-file-size">{{item.size}}</div>
                                        <div class="uploader-list-item-file-name text-ellipsis" :title="item.name">
                                            {{item.name}}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </h-content>
                    <h-footer>
                        <div class="file-manage-upload-btns">
                            <span v-show="typeSelected==2">
                                <button id="uploader_drop" class="h-btn h-btn-primary"><i
                                        class="h-icon-plus"></i>&nbsp;<span>添加文件</span></button>
                                <h-button icon="h-icon-upload" @click="onUploader">上传</h-button>
                            </span>
                            <span v-show="typeSelected==1">
                                <h-button color="primary" @click="onOnlineConfirm">确定选中</h-button>
                            </span>
                            <h-button>取消</h-button>
                        </div>
                    </h-footer>
                </h-layout>
            </h-layout>
        </div>
        <h-modal v-model="createDirectoryModal" :close-on-mask="false">
            <div slot="header">新建文件夹</div>
            <div>
                <h-form v-width="460" :label-width="110" :model="fileDirectoryModel" :rules="validation" ref="form"
                    :top="0.2" show-error-tip>
                    <h-form-item label="文件夹名称" prop="name">
                        <input type="text" v-model="fileDirectoryModel.name" placeholder="只允许英文字母" />
                    </h-form-item>
                </h-form>

            </div>
            <div slot="footer">
                <h-button color="primary" @click="submit">保存</h-button>
                <button class="h-btn" @click="createDirectoryModal=false">取消</button>
            </div>
        </h-modal>
</div>`,
    props: {
        open: {
            type: Boolean,
            default: false
        },
        fileNum: { //文件数量
            type: Number,
            default: 1
        },
        fileSize: { //文件大小
            type: Number,
            default: 300 * 1024
        },
        fileSingleSize: { //文件单个大小
            type: Number,
            default: 300 * 1024
        },
        multiple: { //允许多图选中最大数量
            type: Number,
            default: 2
        },
        accept: { //限制文件类型
            type: Object,
            default: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        }
    },
    data() {
        return {
            open: true,
            uploader: null,
            thumbConfig: {
                url: "/scripts/upload/img/",
                ico: [
                    { ec: ["txt"], img: "txt.png" },
                    { ec: ["rar", "zip", "iso"], img: "zip.png" },
                    { ec: ["wav", "wma", "ogg", "ape", "acc"], img: "audio.png" },
                    { ec: ["avi", "rmvb", "rm", "flash", "mp4", "3gp"], img: "video.png" },
                    { ec: ["exe"], img: "exe.png" },
                    { ec: ["mp3"], img: "mp3.png" },
                    { ec: ["ppt", "pptx"], img: "ppt.png" },
                    { ec: ["doc", "docx"], img: "word.png" },
                    { ec: ["xls", "xlsx"], img: "execl.png" }
                ]
            },
            fileType: [
                {
                    key: 1,
                    name: "图片管理",
                },
                {
                    key: 2,
                    name: "文件上传",
                }
            ],
            fileDirectory: [],
            fileDirectoryModel: {
                name: ""
            },
            validation: {
                required: [
                    'name'
                ],
                rules: {
                    name: {
                        valid: {
                            pattern: /^[a-z]+$/i,
                            message: '只能由英文字母组成,可以是拼音'
                        }
                    }
                }
            },
            createDirectoryModal: false,
            fileDirectorySelected: "pic",
            typeSelected: 1,
            fileListData: [],
            online: { //在线图片
                file: [],
                fileNextMarker: "",
                multiple: this.multiple
            },
            fileNumLimit: this.fileNum,
            fileSizeLimit: this.fileSize,
            fileSingleSizeLimit: this.fileSingleSize,
            uploaderAccept: this.accept,
            fileSizeLimitKB: "",
            fileSingleSizeLimitKB: ""
        }
    },
    methods: {
        //创建
        create() {
            var _this = this;
            _this.uploader = WebUploader.create({
                server: 'http://192.168.50.69/file/upload',
                //选择文件的按钮。可选。
                pick: '#uploader_drop',
                formData: { dirName: "pic" },
                compress: false, //不压缩
                fileNumLimit: _this.fileNumLimit, // 验证文件总数量, 超出则不允许加入队列。
                fileSizeLimit: _this.fileSizeLimit, // 验证文件总大小是否超出限制, 超出则不允许加入队列。
                fileSingleSizeLimit: _this.fileSingleSizeLimit, // 验证单个文件大小是否超出限制, 超出则不允许加入队列
                accept: _this.uploaderAccept
            });

            //当文件添加到上传队列后触发
            _this.uploader.on('filesQueued', function (files) {
                files.forEach(file => {
                    var size = WebUploader.Base.formatSize(file.size, 0, ['B', 'KB', 'MB']);
                    // 创建缩略图
                    _this.uploader.makeThumb(file, function (error, src) {
                        if (error) {
                            _this.fileListData.push({
                                id: file.id,
                                src: _this.thumbSrc(file.ext),
                                name: file.name,
                                size: size,
                                progress: file.processed,
                                closeBtnShow: false,
                                progress: 0,
                                errorCode: 0,
                                errorMsg: ""
                            });
                            return;
                        }
                        _this.fileListData.push({
                            id: file.id,
                            src: src,
                            name: file.name,
                            size: size,
                            progress: file.processed,
                            closeBtnShow: false,
                            progress: 0,
                            errorCode: 0,
                            errorMsg: ""
                        });
                    }, 118, 118);

                })

            });

            //上传前触发
            _this.uploader.on("uploadBeforeSend", function (obj, data, headers) {
                data.dirName = _this.fileDirectorySelected;
            })

            //上传过程中触发，携带上传进度。
            _this.uploader.on("uploadProgress", function (file, percentage) {
                var progress = percentage * 100;
                if (progress >= 100) {
                    progress = 100;
                }
                _this.fileListData.find(f => f.id == file.id).progress = progress;
            })

            // 上传错误
            _this.uploader.on("uploadError", function (file, reason) {
                let data = _this.fileListData.find(f => f.id == file.id);
                data.errorMsg = "上传失败";
                data.errorCode = 2;
            })

            //上传成功
            _this.uploader.on("uploadSuccess", function (file, response) {
                let data = _this.fileListData.find(f => f.id == file.id);
                data.errorMsg = "上传成功";
                data.errorCode = 1;
                _this.$emit('onsuccee', [response.Data.Url]);
            })

            //当validate不通过时以派送错误事件的形式通知调用者。通过
            _this.uploader.on("error", function (type) {
                let msg = "";
                switch (type) {
                    case "Q_EXCEED_NUM_LIMIT":
                        msg = "超出文件总数量";
                        break;
                    case "Q_EXCEED_SIZE_LIMIT":
                        msg = "添加的文件过大";
                        break;
                    case "F_EXCEED_SIZE":
                        msg = "添加的文件过大";
                        break;
                    case "Q_TYPE_DENIED":
                        msg = "不支持该类型文件";
                        break;
                }
                HeyUI.$Message.error(msg);
            })
        },
        //获取文件扩展预览图片
        thumbSrc(name) {
            var img = "file.png";
            this.thumbConfig.ico.forEach(item => {
                var icon = item.ec.find(f => f == name);
                if (icon) {
                    img = item.img;
                }
            })
            return this.thumbConfig.url + img;
        },
        onSenter(index) {
            this.fileListData[index].closeBtnShow = true;
        },
        onleavue(index) {
            this.fileListData[index].closeBtnShow = false;
        },
        onUploader() { //上传
            this.uploader.upload();
        },
        onRemoveFile(id, index) { //移除上传文件
            this.uploader.removeFile(id, true);
            this.fileListData.splice(index, 1);
        },
        onChangeType(data) { //操作类型改变
            //console.log(data);
        },
        onOnlineSelected(index) { //在线管理选中文件切换
            //可能只选中一张
            var ck = this.online.file[index].checked;
            if (ck) {
                ck = false;
            } else {
                ck = true;
            }

            //选中当前判断
            if (ck) {
                var ml = this.online.multiple;
                var count = this.online.file.filter(f => f.checked == true).length;
                if (count >= ml) {
                    return;
                }
            }
            this.online.file[index].checked = ck;
        },
        onOnlineConfirm() { //在线管理确定选中图片
            var data = this.online.file.filter(f => f.checked == true);
            var srcs = [];
            if (data.length > 0) {
                srcs = data.map(m => m.src);
            }
            this.$emit('onsuccee', srcs);
        },
        onOnlineScroll(e) {
            if (e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight) {
                this.loadFile();
            }
        },
        onChangeDirectory() { //改变目录清空加载文件重新加载指定文件夹
            this.online.file = [];
            this.online.fileNextMarker = "";
            this.loadFile();
        },
        //加载目录
        loadDirectory() {
            var _this = this;
            $http.post("file/directoryList", {}, function (d) {
                let _data = [];
                d.DirData.forEach(item => {
                    _data.push({
                        key: item,
                        name: item
                    })
                });
                _this.fileDirectory = _data;
            })
        },
        //加载文件
        loadFile() {
            let _this = this;
            //没有数据加载
            if (_this.online.fileNextMarker == null) {
                return;
            }
            var postData = {
                Marker: _this.online.fileNextMarker,
                DirName: _this.fileDirectorySelected
            };
            $http.post("file/fileList", postData, function (d) {
                d.Url.forEach(item => {
                    _this.online.file.push({
                        src: item,
                        checked: false
                    })
                });
                _this.online.fileNextMarker = d.NextMarker;
            })
        },
        submit() {
            let _this = this;
            let validResult = _this.$refs.form.valid();
            if (!validResult.result) {
                return;
            }
            //添加目录
            $http.post("file/createDirectory", _this.fileDirectoryModel, function (d, code, msg) {
                if (code == 0) {
                    _this.loadDirectory();
                }
                HeyUI.$Message(msg);
            })
        },
        formatKB() {
            this.fileSingleSizeLimitKB = WebUploader.Base.formatSize(this.fileSingleSizeLimit, 0, ['B', 'KB', 'MB']);
            this.fileSizeLimitKB = WebUploader.Base.formatSize(this.fileSizeLimit, 0, ['B', 'KB', 'MB']);
        }

    }, mounted() {
        this.loadDirectory();
        this.loadFile();
        this.create();
        this.formatKB();
    }
})
